/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View, TouchableOpacity, Image, ScrollView, processColor, NativeAppEventEmitter
} from 'react-native';
import  theme from '../config/theme'
import {px2dpH, px2dpW} from "../config/px2dp"
import Chart from "../widget/Chart"
import  ChartConfig from '../config/ChartConfig'
type Props = {};
import _ from 'lodash';
const purple = processColor('#8A2BEA')
const green = processColor('#00ff00');
const yellow = processColor('#ffff00');
const red = processColor('#ee7733');

import net from 'react-native-tcp';
import  TcpManager from "../manager/TcpManager"
import OrientationUtil from '../util/OrientationUtil'
import UtilManager from '../util/UtilManager'
// import Slide from  '../widget/siftmenu/SlidSegmentedControl'
//import Slide from  '../widget/siftmenu/SiftListViewNew'
import TopMenu from "../widget/siftmenu/TopMenu";

export default class DetailChartScene extends Component<Props> {
    static navigationOptions = ({navigation}) => ({
        header: null
    });


    constructor(props) {
        super(props)

        this.state = {
            reload: false,
        }

        this.chartName = ""
        this.bottomtext = [1, 2, 3]

        this.sSeries = []
        this.wenshidu = {}
        this.fenbeidata = {}

        this.dataz = {};
        this.dataSpinner = []


        this.index = {
            beforeLeft: 0,
            beforeRight: 0,
            currentLeft: 0,
            currentRight: 0,
        }

        this.getx = {leftx: -1, rightx: -1}


        switch (theme.datainfo.groups) {
            case 1:
                this.dataSpinner = [
                    {title: 'S1', subtitle: ''},
                    {title: '温湿度', subtitle: ''},
                    {title: '分贝', subtitle: ''},
                ]
                break
            case 2:
                this.dataSpinner = [
                    {title: 'S1', subtitle: ''},
                    {title: 'S2', subtitle: ''},
                    {title: '温湿度', subtitle: ''},
                    {title: '分贝', subtitle: ''},
                ]
                break
            case 3:
                this.dataSpinner = [
                    {title: 'S1', subtitle: ''},
                    {title: 'S2', subtitle: ''},
                    {title: 'S3', subtitle: ''},
                    {title: '温湿度', subtitle: ''},
                    {title: '分贝', subtitle: ''},
                ]
                break
        }

        this.config = [
            {
                type: 'subtitle',
                selectedIndex: this.getSelectedIndex(),
                data: this.dataSpinner
            }
        ];

        this.chartlength = 0;
    }

    getSelectedIndex() {
        switch (this.props.navigation.state.params.name) {
            case "S1":
                this.chartName = "S1"
                return 0;
                break
            case "S2":
                this.chartName = "S2"
                return 1;
                break
            case "S3":
                this.chartName = "S3"
                return 2;
                break
            case "温湿度":
                this.chartName = "温湿度"
                return theme.datainfo.groups;
                break
            case "分贝":
                this.chartName = "分贝"
                return theme.datainfo.groups + 1;
                break
        }
    }

    reload() {
        this.setState({reload: !this.state.reload})
    }

    updateDatez() {
        switch (this.props.navigation.state.params.name) {
            case "S1":
                this.chartName = "S1"
                this.dataz = this.sSeries[0]
                this.index = {
                    currentLeft: 0,
                    currentRight: this.sSeries[0].dataSets[0].values.length - 1,
                }

                this.chartlength = this.sSeries[0].dataSets[0].values.length - 1

                this.bottomtext = theme.getDetailBottom(0, this.chartlength, this.chartlength)

                this.reload()
                break
            case "S2":
                this.chartName = "S2"
                this.dataz = this.sSeries[1]
                this.index = {
                    currentLeft: 0,
                    currentRight: this.sSeries[1].dataSets[0].values.length - 1,
                }
                this.chartlength = this.sSeries[0].dataSets[0].values.length - 1
                this.bottomtext = theme.getDetailBottom(0, this.chartlength, this.chartlength)
                this.reload()
                break
            case "S3":
                this.chartName = "S3"
                this.dataz = this.sSeries[2]
                this.index = {
                    currentLeft: 0,
                    currentRight: this.sSeries[2].dataSets[0].values.length - 1,
                }
                this.chartlength = this.sSeries[0].dataSets[0].values.length - 1
                this.bottomtext = theme.getDetailBottom(0, this.chartlength, this.chartlength)
                this.reload()
                break
            case "温湿度":
                this.chartName = "温湿度"
                this.dataz = this.wenshidu
                this.index = {
                    currentLeft: 0,
                    currentRight: this.wenshidu.dataSets[0].values.length - 1,
                }
                this.chartlength = this.wenshidu.dataSets[0].values.length - 1
                this.bottomtext = theme.getDetailBottom(0, this.chartlength, this.chartlength)
                this.reload()
                break
            case "分贝":
                this.chartName = "分贝"
                this.dataz = this.fenbeidata
                this.index = {
                    currentLeft: 0,
                    currentRight: this.fenbeidata.dataSets[0].values.length - 1,
                }
                this.chartlength = this.fenbeidata.dataSets[0].values.length - 1
                this.bottomtext = theme.getDetailBottom(0, this.chartlength, this.chartlength)
                this.reload()
                break
        }


    }

    updateIndex(left, right) {
        this.index.beforeLeft = this.index.currentLeft

        this.index.beforeRight = this.index.currentRight


        if (left < right) {
            this.index.currentLeft = left
            this.index.currentRight = right
        } else {
            this.index.currentLeft = right
            this.index.currentRight = left
        }

        this.bottomtext = theme.getDetailBottom(this.index.currentLeft, this.index.currentRight, this.chartlength)
        theme.getAverByLeftRight(this.index.currentLeft, this.index.currentRight, this.chartName)
        this.reload()
        console.log("this.index", this.index)
    }


    componentDidMount() {

        OrientationUtil.screenLockToLandscape()
        let n = 1;// theme.datainfo.rate;
        switch (theme.datainfo.groups) {
            case 1:
                this.sSeries = [ChartConfig.getData(theme.yvalue1, n, false)]
                break
            case 2:
                this.sSeries = [ChartConfig.getData(theme.yvalue1, n, false), ChartConfig.getData(theme.yvalue2, n, false)]
                break
            case  3:
                this.sSeries = [ChartConfig.getData(theme.yvalue1, n, false), ChartConfig.getData(theme.yvalue2, n, false), ChartConfig.getData(theme.yvalue3, n, false)]
                break
        }

        if (theme.air && theme.temp && theme.wet) {
            this.wenshidu = ChartConfig.getDataThree(theme.air, theme.temp, theme.wet, 1, false)
        }
        if (theme.db) {
            this.fenbeidata = (ChartConfig.getDataLine(theme.db, 1, false))
        }

        this.updateDatez()       // this.reload()

        //   this.props.navigation.setParams({clickRight: this.goToSetting.bind(this), clickLeft: this.goTestTcp.bind(this)})

        //     this.reload()
    }


    handleSelect(event) {


        let entry = event.nativeEvent

        console.log(event.nativeEvent)
        if (this.flagtimeout) {
            // console.log(event.nativeEvent.x && event.nativeEvent.y)
            if (event.nativeEvent) {
                console.log("left or right", event.nativeEvent.x)

                if (event.nativeEvent.x == 0) {
                    console.log("x===0")
                    this.getx.leftx = event.nativeEvent.x
                    this.getx.rightx = -1
                } else {
                    if (this.getx.leftx == -1) {
                        console.log("this.getx.left", this.getx.leftx)
                        console.log("x!=0 in left")
                        this.getx.leftx = event.nativeEvent.x
                    } else {
                        console.log("x!=0 in right")
                        this.getx.rightx = event.nativeEvent.x
                        console.log("this.getx", this.getx)
                        this.updateIndex(this.getx.leftx, this.getx.rightx)
                        this.getx = {leftx: -1, rightx: -1}
                        this.flagtimeout = false
                    }
                }

            } else {
                console.log("into the else...")
            }
        }
    }

    onChange(event) {
        console.log(event)

        this.clickForIndex()

    }

    clickForIndex() {
        this.flagtimeout = true
        this.timeout && clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
            this.performClick()
        }, 10)
    }

    fenBeiOnRight() {
        console.log("fenBeiOnRight");

    }


    chartClick(zz) {
        //   console.log(zz)
    }


    componentWillUnmount() {
        NativeAppEventEmitter.emit('gobacktohome', 'gobacktohome')
    }


    renderContent = () => {
        return null;
        // alert(this.state.data.title)
    };

    onSelectMenu = (index, subindex, data) => {
        // this.setState({index, subindex, data});

        console.log(index, subindex, data)
        switch (data.title) {
            case "S1":
                this.chartName = "S1"
                this.dataz = this.sSeries[0]
                this.chartlength = this.dataz.dataSets[0].values.length - 1
                this.reload()
                break;
            case "S2":
                this.chartName = "S2"
                this.dataz = this.sSeries[1]
                this.chartlength = this.dataz.dataSets[0].values.length - 1
                this.reload()
                break;
            case "S3":
                this.chartName = "S3"
                this.dataz = this.sSeries[2]
                this.chartlength = this.dataz.dataSets[0].values.length - 1
                this.reload()
                break;
            case "温湿度":
                this.chartName = "温湿度"
                this.dataz = this.wenshidu

                this.chartlength = this.dataz.dataSets[0].values.length - 1
                this.reload()
                break;
            case "分贝":
                this.chartName = "分贝"
                this.dataz = this.fenbeidata
                this.chartlength = this.dataz.dataSets[0].values.length - 1
                this.reload()
                break;
        }
    };

    renderButtonBar() {
        return (
            <View style={styles.btnbarbg}>

            </View>)
    }

    performClick() {
        UtilManager.performClick(68, 400).then((suc) => {

        }, (fail) => {
        })
        // console.log("porwidth", theme.getPorScreenWidth() * theme.pr)
        // console.log("landwidth", theme.getLandScreenWidth() * theme.pr)
        // console.log("right", ( (theme.getLandScreenWidth() - px2dpW(8)) / 5 * 4 - 10) * theme.pr)
        UtilManager.performClick(((theme.getLandScreenWidth() - px2dpW(8)) / 5 * 4 - 25) * theme.pr, 400).then((suc) => {

        }, (fail) => {
        })
    }

    renderButtonBar2() {

        return (
            <View
                style={{position:'absolute',flex:1,width:theme.getLandScreenWidth(),top:Platform.OS==="ios"?px2dpH(20):0}}>
                <TopMenu title={"zz"} style={{position:'absolute',top:20,flex:1,width:theme.getLandScreenWidth()}}
                         config={this.config}
                         onSelectMenu={this.onSelectMenu}
                         renderContent={this.renderContent}/>

            </View>

        )
    }

    renderScrolltable() {

        return (
            <Chart
                name={this.chartName}
                ifThree={this.chartName=="温湿度"}
                ifCustomRight={this.chartName=="分贝"}
                onRight={this.fenBeiOnRight.bind(this)}
                containStyle={{ width:theme.getLandScreenWidth(),flex:5,paddingBottom:px2dpH(10)}}
                xAxis={ChartConfig.xAxisA}
                yAxis={ChartConfig.yAxisA}
                data={this.dataz}
                onSelect={this.handleSelect.bind(this)}
                onChange={this.onChange.bind(this)}
                scaleXEnabled={true}
                scaleYEnabled={false}
                pinchZoom={false}
                chartDisClickable={true}
                onChartPress={this.chartClick.bind(this)}
                doubleTapToZoomEnabled={false}
                bottomtext={this.bottomtext}
                rightValue={this.chartName==="温湿度"?theme.detailaverArr:theme.detailaver}
            />

        )
    }

    render() {
        return (
            <View style={styles.container}>
                {this.renderButtonBar()}

                {this.renderScrolltable()}
                {this.renderButtonBar2()}
            </View>
        );
    }


}


const
    styles = StyleSheet.create({
        container: {
            flex: 1,
            alignItems: 'center',
            backgroundColor: '#E5ECFF',
        },
        btnbarbg: {
            backgroundColor: '#ffffff',
            alignItems: 'center',
            flexDirection: 'row',
            justifyContent: 'space-around',
            flex: 1
        },

        btnbg: {
            width: px2dpW(100),
            height: px2dpH(40),
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'rgb(68,154,208)',
            borderRadius: px2dpW(4)
        },
        btntext: {
            color: '#ffffff',
            fontSize: 13
        },


        chart: {
            flex: 1
        }

    });
